<?php
namespace s_time_task;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'TimerBase.php'; // 该文件必须引入，该文件是框架的初始化

/**
 * 多进程测试
 *
 * Class Process
 * @package s_time_task
 */
class Process
{
    public $workers = [];
    public $master_pid = null;
    public $finished_num = 0;
    public $urls = [
        'https://www.baidu.com',
        'https://sina.com.cn',
        'http://news.pconline.com.cn/1165/11651127.html',
        'https://www.nanrenwo.net/zlht/141729.html',
        'http://www.lc123.net/xw/rd/2018-08-27/981629.html'
    ];

    public function index(){
        $this->master_pid = posix_getpid();
        for ($i = 0; $i < count($this->urls); $i++)
        {
            //创建子进程
            $process = new \swoole_process(function (\swoole_process $worker) use($i){
                $content = $this->urlData($this->urls[$i]);
                echo $content.PHP_EOL;
                $worker->exit(0); // 子进程退出
            }, true);

            $pid = $process->start();
            $this->workers[$pid] = $process;
        }

        // 读取子进程的消息
        foreach ($this->workers as $process) {
            echo $process->read();
        }

        // 回收子进程
        $this->wait();
    }

    //模拟请求url 内容.耗时6s
    public function urlData($url)
    {
        sleep(1);
        return $url . '   success' . PHP_EOL;
    }


    public function wait() {
        \swoole_process::signal(SIGCHLD, function($sig) {
            //必须为false，非阻塞模式
            while($ret =  \swoole_process::wait(false)) {
                sleep(2);
                \swoole_process::kill($this->master_pid);
                $pids = array_keys($this->workers);
                if (array_search($ret['pid'], $pids) !== false) {
                    $this->finished_num += 1;
                    if ($this->finished_num === count($this->urls)) {
                        \swoole_process::kill($this->master_pid);
                    }
                }
            }
        });
    }

}

echo date("Y-m-d H:i:s").PHP_EOL;
$processM = new Process();
$processM->index();
echo date("Y-m-d H:i:s") . PHP_EOL;